import json

from django import http
from django.contrib.auth.mixins import LoginRequiredMixin
from django.shortcuts import render

# Create your views here.
from django.utils import timezone
from django.views import View
from django_redis import get_redis_connection

from apps.goods.models import SKU
from apps.orders.models import OrderInfo, OrderGoods
from apps.users.models import Address
from utils.response_code import RETCODE


class PlaceOrderView(LoginRequiredMixin, View):
    def get(self, request):
        user = request.user
        addresses = Address.objects.filter(user=user, is_deleted=False)
        redis_coon = get_redis_connection('carts')
        carts_sku_id_count = redis_coon.hgetall('user_id:%s' % user.id)
        carts_selected = redis_coon.smembers('user_selected:%s' % user.id)
        carts_dict = {}
        for sku_id in carts_selected:
            carts_dict[int(sku_id)] = int(carts_sku_id_count[sku_id])
        sku_ids = carts_dict.keys()
        skus = SKU.objects.filter(id__in=sku_ids)
        total_count = 0
        total_amount = 0
        for sku in skus:
            sku.count = carts_dict[sku.id]
            sku.amount = (carts_dict[sku.id] * sku.price)

            total_count += carts_dict[sku.id]
            total_amount += (carts_dict[sku.id] * sku.price)
        freight = 10
        context = {
            'addresses': addresses,
            'skus': skus,
            'total_count': total_count,
            'total_amount': total_amount,
            'freight': freight,
            'payment_amount': total_amount + freight,

        }

        return render(request, 'place_order.html', context)


class OrderCommitView(LoginRequiredMixin, View):
    def post(self, request):
        json_dict = json.loads(request.body.decode())
        address_id = json_dict.get('address_id')
        pay_method = json_dict.get('pay_method')
        if not all([address_id, pay_method]):
            return http.JsonResponse({'code': RETCODE.NODATAERR, 'errmsg': '参数不全'})
        try:
            addresses = Address.objects.get(pk=address_id)
        except Address.DoesNotExist:
            return http.JsonResponse({'code': RETCODE.DBERR, 'errmsg': '地址不存在'})
        user = request.user
        order_id = timezone.localtime().strftime('%Y%m%d%H%M%S') + '%09d' % user.id
        from decimal import Decimal
        total_amount = Decimal('0')
        freight = Decimal('10')
        total_count = 0
        try:
            pay_method = int(pay_method)
        except:
            pass

        if pay_method not in [OrderInfo.PAY_METHODS_ENUM['CASH'], OrderInfo.PAY_METHODS_ENUM['ALIPAY']]:
            return http.JsonResponse({'code': RETCODE.PARAMERR, 'errmsg': '参数错误'})
        if pay_method == OrderInfo.PAY_METHODS_ENUM['CASH']:
            status = OrderInfo.ORDER_STATUS_ENUM['UNSEND']
        else:
            status = OrderInfo.ORDER_STATUS_ENUM['UNPAID']
        from django.db import transaction
        with transaction.atomic():
            save_point = transaction.savepoint()
            order = OrderInfo.objects.create(
                order_id=order_id,
                user=user,
                address=addresses,
                total_count=total_count,
                total_amount=total_amount,
                freight=freight,
                pay_method=pay_method,
                status=status,
            )
            redis_conn = get_redis_connection('carts')
            sku_id_counts = redis_conn.hgetall('user_id:%s' % user.id)
            selected_ids = redis_conn.smembers('user_selected:%s' % user.id)
            carts = {}
            for id in selected_ids:
                carts[int(id)] = int(sku_id_counts[id])
            sku_ids = carts.keys()
            for sku_id in sku_ids:
                try:
                    sku = SKU.objects.get(pk=sku_id)
                except:
                    return http.HttpResponseBadRequest('数据库链接错误')
                count = carts[sku_id]
                if count > sku.stock:
                    return http.HttpResponseBadRequest('库存不足')
                old_stock = sku.stock
                new_stock = old_stock - count
                new_sales = old_stock + count
                rect = SKU.objects.filter(stock=old_stock, pk=sku.id).update(stock=new_stock, sales=new_sales)
                if rect == 0:
                    transaction.savepoint_commit(save_point)
                    return http.JsonResponse({"code": RETCODE.NODATAERR, 'errmsg': '库存不足'})
                #
                # sku.stock -= count
                # sku.sales += count
                # sku.save()
                OrderGoods.objects.create(
                    order=order,
                    sku=sku,
                    count=count,
                    price=sku.price
                )
                order.total_count += count
                order.total_amount += count * sku.price
            order.save()
            transaction.savepoint_commit(save_point)
            return http.JsonResponse({
                'code': RETCODE.OK,
                'errmsg': 'ok',
                'order_id': order.order_id,
                'pay_amount': order.total_amount
            })


class OrderSuccessfulView(View):
    def get(self, request):
        order_id = request.GET.get('order_id')
        payment_amount = request.GET.get('payment_amount')
        pay_method = request.GET.get('pay_method')
        context = {
            'order_id': order_id,
            'payment_amount': payment_amount,
            'pay_method': pay_method,
        }

        return render(request, 'order_success.html', context)


class OrderCommentView(LoginRequiredMixin, View):
    def get(self, request):

        order_id = request.GET.get('order_id')
        user = request.user
        try:
            order = OrderInfo.objects.get(pk=order_id, user=user)
        except OrderInfo.DoesNotExist:
            return http.HttpResponseBadRequest('订单不存在')
        try:
            goods = OrderGoods.objects.filter(order=order, is_commented=False)
        except OrderGoods.DoesNotExist:
            return http.HttpResponseBadRequest('不存在未评价商品')
        sku_list = []
        for good in goods:
            sku_list.append({
                'default_image_url': good.sku.default_image.url,
                'name': good.sku.name,
                'price': str(good.sku.price),
                'score': good.score,
                'sku_id': good.sku.id,
                'order_id': good.order.order_id,
                'comment': good.comment,
                'is_anonymous': str(good.is_anonymous),
            })
        context = {
            'skus': sku_list
        }
        return render(request, 'goods_judge.html', context)

    def post(self, request):
        data = json.loads(request.body.decode())
        order_id = data.get('order_id')
        sku_id = data.get('sku_id')
        comment = data.get('comment')
        score = data.get('score')
        is_anonymous = data.get('is_anonymous')
        if not all([order_id, sku_id, score, comment]):
            return http.HttpResponseForbidden('缺少必传参数')
        try:
            order = OrderInfo.objects.get(pk=order_id, user=request.user,
                                          status=OrderInfo.ORDER_STATUS_ENUM['UNCOMMENT'])
        except OrderInfo.DoesNotExist:
            return http.HttpResponseBadRequest('订单不存在')
        try:
            sku = SKU.objects.get(id=sku_id)
        except SKU.DoesNotExist:
            return http.HttpResponseForbidden('参数sku_id错误')
        OrderGoods.objects.filter(order=order, sku=sku).update(
            comment=comment,
            score=score,
            is_anonymous=is_anonymous,
            is_commented=True
        )
        sku.comments += 1
        sku.save()
        # 没有想到的
        sku.spu.comments += 1
        sku.spu.save()
        if OrderGoods.objects.filter(order_id=order_id, is_commented=False).count() == 0:
            OrderInfo.objects.filter(order_id=order_id).update(status=OrderInfo.ORDER_STATUS_ENUM['FINISHED'])

        return http.JsonResponse({'code': RETCODE.OK, 'errmsg': '评价成功'})
